<template lang="html">
  <article id="views-order_confirm">
    <ConfirmDetail
      v-on:selectCoupon="toggleShowCoupon"
      :detail="confirmDetail"
      :currentCouponId="currentCouponId"
    ></ConfirmDetail>
    <section class="selectCoupon-container" :style="{ transform: `translate3d(${isShowSelectCoupon ? `100%`:0},0,0)` }">
      <SelectCoupon
        v-on:selectCoupon="selectCoupon"
        :couponList="couponList"
      ></SelectCoupon>
    </section>
    <button type="button" class="confirmBtn" @click="payOrder()">确认订单（<em>￥</em> <em class="price">{{confirmDetail && confirmDetail.currentPrice}} RMB</em> ）</button>
  </article>
</template>

<script>
import utils from '@/lib/utils'
import superagent from 'superagent'
import authMiddleWare from '@/lib/auth-middleware'
export default {
  components: {
    ConfirmDetail: require('@/components/confirm_detail'),
    SelectCoupon: require('@/components/confirm_select_coupon')
  },
  data(){
    return {
      isShowSelectCoupon: false,
      confirmDetail: null,
      couponList: [],
      currentCouponId: '',
    }
  },
  methods: {
    toggleShowCoupon(){
      this.isShowSelectCoupon = !this.isShowSelectCoupon
    },
    payOrder(){
      this.confirmOrder({
        subjectId: this.$route.params.subject_id,
        couponId: this.currentCouponId
      })
      .then(result => {
        if(result.isFree == 1){
          let self = this
          utils.modal({
            title: '支付提示',
            desc: '预约成功',
            callback: function(){
              self.$router.push({ path: '/personal' })
            }
          })
          return Promise.resolve(false)
        } else {
          return this.getPayParameter(result.orderId)
        }
      })
      .then(result => {
        if(!result) return

        let self = this
        result = result.paymentConfigs
        this.$store.dispatch('wxPay', {
          timestamp: result.timestamp,
          nonceStr: result.nonceStr,
          _package: result.package,
          signType: result.signType,
          paySign: result.paySign,

          callback: function(){
            utils.toast('支付成功')
            self.$router.push({ path: '/personal' })
          }
        })
      })
      .catch(e => {
        //下单失败流程
        if(e.hasOwnProperty('errCode')){
          let errorInfo = ''
          switch (e.errCode) {
            case -1:
              errorInfo = '已经下过单，正在处理中'
              break;
            case -2:
              errorInfo = '排队成功'
              break;
            case -3:
              errorInfo = '等待支付'
              break;
            case -4:
              errorInfo = '您在这个时间段内已经有一门课程了'
              break;
            case -5:
              errorInfo = '该课程不接受此优惠券，请重新选择'
              break;
            case -6:
              errorInfo = '服务器错误，请联系客服'
              break;
            default:
              errorInfo = '支付失败，请联系客服'
          }
          utils.modal({
            title: '支付失败',
            desc: errorInfo
          })
        }
      })
      // this.$store.dispatch('toggleIsLoading')
      // setTimeout(() => {
      //   this.$store.dispatch('toggleIsLoading')
      //   utils.toast('约课成功！')
      //   setTimeout(() => {
      //     this.$router.push({ path: '/' })
      //   }, 300)
      // }, 1000)
    },
    getPayParameter(orderId){
      return new Promise((resolve, reject) => {
        superagent.get(`/api/WxCommon/payOrder/${orderId}`)
          .use(authMiddleWare())
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('getPayParameter error'))
              }
            }
          })
      })
    },
    confirmOrder({ subjectId, couponId }){
      let opt = {
        subjectId,
      }
      if(couponId){
        opt.coupon_id = couponId
      }
      return new Promise((resolve, reject) => {
        superagent.post('/api/order/buy')
          .use(authMiddleWare())
          .query(opt)
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('confirmOrder error'))
              }
            }
          })
      })
    },
    getConfirmDetail({ subjectId, couponId }){
      return new Promise((resolve, reject) => {
        let opt = {
          subjectId
        }
        if(couponId){
          opt.coupon_id = couponId
        }
        superagent.post('/api/order/check')
          .use(authMiddleWare())
          .query(opt)
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              reject(new Error('getConfirmDetail error'))
            }
          })
      })
    },
    getCouponList(){
      return new Promise((resolve, reject) => {
        superagent.post('/api/member/my_coupon')
          .use(authMiddleWare())
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              reject(new Error('getCouponList error'))
            }
          })
      })
    },
    selectCoupon(id){
      this.toggleShowCoupon()
      this.currentCouponId = id
      //选择优惠券后更新订单详情
      this.$store.dispatch('toggleIsLoading')
      this.getConfirmDetail({
        subjectId: this.$route.params.subject_id,
        couponId: this.currentCouponId
      })
      .then(data => {
        this.$store.dispatch('toggleIsLoading')
        this.confirmDetail = data
      })
    }
  },
  beforeRouteEnter(to, from, next){
    let result = utils.checkLocator()
    if(typeof result === 'string'){
      if(window.location.hash !== `#${to.path}`){//判断进入该路由的方法为app内路由跳转还是绝对地址跳转
        result = result.replace(`#${from.path}`, `#${to.path}`)
      }
      window.location.replace(result)//video页与confirm页存在一个为了补充？符号的重定向，因此这个重定向需要使用replace方法去除当前页面的访问历史
    } else {
      next()
    }
  },
  created(){
    this.getConfirmDetail({
      subjectId: this.$route.params.subject_id
    })
    .then(data => {
      this.couponList = data.coupon
      this.confirmDetail = data
    })
  }
}
</script>

<style lang="scss" scoped>
@import "../css/config";
#views-order_confirm{
  position: relative;
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
  padding: 0 40px;
  padding-bottom: $backbtn-height;
  background-color: $common-bg;
  overflow: hidden;
  .selectCoupon-container{
    position: fixed;
    z-index: 990;
    top: 0;
    right: 100%;
    width: 100%;
    height: 100%;
    transition: transform 0.5s ease-in-out;
  }
  .confirmBtn{
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: $backbtn-height;
    background-color: $common-red;
    font-size: 33px;
    color: #fff;
    font-weight: 100;
    em{
      font-size: 25px;
    }
    .price{
      font-size: 33px;
      font-weight: bold;
    }
    &:active{
      color: $active-font;
      background-color: $active-bg;
    }
  }
}
</style>
